/*
    This file is part of open-wars <http://code.google.com/p/open-wars/>.

    open-wars is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    open-wars is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with open-wars.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <opengl-input.h>

// Keyboard Callbacks
IInputCallback onKeyDown;
IInputCallback onKeyUp;

// Mouse Callbacks
IInputCallback onMouseMove;
IInputCallback onMouseButtonDown;
IInputCallback onMouseButtonUp;

// General Global Variables
static OpenGLInput *glInput;
static bool glKeyboardState[256];
static bool glMouseButtonState[3];
static unsigned int glMouseX, glMouseY;


static void OpenGLInputKeyPressed (unsigned char key, int x, int y)
{
    glKeyboardState[key] = TRUE;
}

static void OpenGLInputKeyReleased (unsigned char key, int x, int y)
{
    glKeyboardState[key] = FALSE;
}

static void OpenGLInputMouseEvent(int button, int state, int x, int y)
{
    glMouseButtonState[button] = (state == GLUT_DOWN);
    glMouseX = x;
    glMouseY = y;

    if (state == GLUT_DOWN) 
    {
        if (onMouseButtonDown)
            (*onMouseButtonDown)(NULL);
    } else {
        if (onMouseButtonUp)
            (*onMouseButtonUp)(NULL);
    }
}

static void OpenGLInputMouseMoveEvent(int x, int y)
{
    glMouseX = x;
    glMouseY = y;

    if (onMouseMove)
        (*onMouseMove)(NULL);
}

OpenGLInput::OpenGLInput()
{
}

MousePosResult OpenGLInput::GetMousePos(void)
{
    MousePosResult res;
    res.mouseX = glMouseX;
    res.mouseY = glMouseY;
    return res;
}

void OpenGLInput::Initialize(void)
{
    glInput = this;
    for (UINT16 i = 0; i < 256; i++)
        glKeyboardState[i] = FALSE;

    glutKeyboardFunc(OpenGLInputKeyPressed);
    glutKeyboardUpFunc(OpenGLInputKeyReleased);
    glutMouseFunc(OpenGLInputMouseEvent);
    glutMotionFunc(OpenGLInputMouseMoveEvent);
    glutPassiveMotionFunc(OpenGLInputMouseMoveEvent);
}
